package com.example.demo.controller;

import com.example.demo.config.RocketMessageProducer;
import com.example.demo.framework.IStudent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Controller
@RequestMapping("/home")
public class HomeController {


    private IStudent iStudent;
    public HomeController(IStudent iStudent){
        this.iStudent = iStudent;
    }
    @RequestMapping("/index")
    //@ResponseBody
    public String index(HttpServletRequest request, HttpServletResponse response, Model model){
        model.addAttribute("name","wang");
        iStudent.sayName();

        //RocketMessageProducer.producerMsg("RocketProdTagTest","RocketProdKeyTest","RocketProdBodyTest");
        return "index";
    }

    @RequestMapping("/get1")
    public ResponseEntity<byte[]> get(String Path) {
        //将获取文件的路径准备好
        File file = new File("D:\\TDDownload\\477010.mp3");

        //通过readAllBytes将file路径的文件 读成字节形式
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bb = new byte[1000];
            if (a != null) {
                //读取成功，将其返回给前段
                fileInputStream.read(bb);
                return ResponseEntity.ok(a);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读取失败
        return ResponseEntity.badRequest().build();
    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> get2(String path){
        //我们要先获取到该音乐保存在服务器下的路径信息!
        try {
            byte[] fileByte = null;
            //获取到文件对象
            File file = new File("D:\\TDDownload\\477010.mp3");
            //获取到该文件对象的路径信息
            Path filepath =  file.toPath();
            //读取文件中的所有字节
            fileByte = Files.readAllBytes(filepath);
            return ResponseEntity.ok(fileByte);
        }catch (IOException e){
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }
}
